package com.water.quality.testing.utils;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.water.quality.testing.dao.ObservationPoint;
import com.water.quality.testing.dao.WaterData;
import com.water.quality.testing.mapper.ObservationPointMapper;
import com.water.quality.testing.service.ObservationPointService;
import com.water.quality.testing.service.WaterDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 水质数据定时生成工具类
 */
@Service
public class WaterDataScheduler {

    @Autowired
    private WaterDataGenerator generator;

    @Autowired
    private WaterDataService waterDataService;

    @Autowired
    private ObservationPointService pointService;

    @Autowired
    private ObservationPointMapper observationPointMapper;

    //@Scheduled(fixedRate = 10000)
    @Transactional(rollbackFor = Exception.class) // 使用 @Transactional 注解确保在发生异常时进行回滚
    public void generateAndSaveData() {
        // 从 pointService 获取所有的观测点
        List<ObservationPoint> points = pointService.getAllObservationPoints();
        // 遍历所有观测点
        for (ObservationPoint point : points) {
            // 获取当前观测点的最新水数据
            WaterData lastData = waterDataService.getLatestWaterData(point.getId());
            // 使用生成器生成新的水数据
            WaterData newData = generator.generateNewData(point.getId(), lastData);
            // 使用 LambdaUpdateWrapper 构建更新条件
            LambdaUpdateWrapper<ObservationPoint> wrapper = Wrappers.lambdaUpdate(ObservationPoint.class)
                    // 根据观测点 ID 匹配记录
                    .eq(ObservationPoint::getId, point.getId())
                    // 设置新的质量等级
                    .set(ObservationPoint::getQualityLevel, newData.getQualityLevel());
            // 更新观测点的质量等级
            observationPointMapper.update(null, wrapper);
            // 保存新生成的水数据
            waterDataService.saveWaterData(newData);
            // 打印生成并保存的新数据的信息
            System.out.println("Generated and saved new data for point " + point.getName() + ": " + newData);
        }
    }
}
